import { View } from "@tarojs/components";
import clsx from "clsx";
import React, { useMemo, type CSSProperties } from "react";
import styles from './index.module.css';

interface Props<T extends string | number | boolean> {
  className?: string
  activeColor?: string
  color?: string
  options: IOption<T>[]
  value: T
  onChange(value: T, option: IOption<T>): void
  renderItem(option: IOption<T>, active: boolean): React.ReactNode
}
export function GpSwitch<T extends string | number | boolean>({ className, activeColor = "#FFFFFF", color = "#F4F6FC", options, value, onChange, renderItem }: Props<T>) {
  const style: CSSProperties = {
    backgroundColor: color
  }
  const floaterStyle = useMemo<CSSProperties>(() => {
    const index = options.findIndex((option) => option.value === value)
    let sx: string | number = 0
    if (~index && index) {
      sx = `${index}00%`
    }
    return {
      backgroundColor: activeColor,
      width: Number((1 / options.length) * 100).toFixed(2) + "%",
      transform: `translateX(${sx})`
    }
  }, [options, value])
  function handleSwitch(option: IOption<T>) {
    if (option.value === value) return
    onChange(option.value, option)
  }
  return (
    <View className={clsx("box-border h-[64px] rounded-[32px] p-[4px]", className)} style={style}>
      <View className="relative flex flex-row items-center w-full h-full rounded-[inherit]">
        <View className={clsx("absolute z-0 top-0 left-0 bottom-0 rounded-[inherit]", styles.floater)} style={floaterStyle}></View>
        {
          options.map((option, index) => (
            <View key={index} className="relative flex flex-1 flex-nowrap justify-center items-center" onClick={() => handleSwitch(option)}>
              {renderItem(option, option.value === value)}
            </View>
          ))
        }
      </View>
    </View>
  )
}
